'''
Author: 红星大哥 zhxlx@foxmail.com
Date: 2024-07-11 10:55:02
LastEditors: 红星大哥 zhxlx@foxmail.com
LastEditTime: 2024-07-11 14:50:03
FilePath: \esp8266\app_web.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
# micropython web.py

'''
help('modules')
__main__          dht               machine           select
_asyncio          ds18x20           math              socket
_boot             errno             micropython       ssl
_espnow           esp               mip/__init__      struct
_onewire          espnow            neopixel          sys
_webrepl          flashbdev         network           time
apa102            framebuf          ntptime           tls
array             gc                onewire           uctypes
binascii          hashlib           os                urequests
btree             heapq             platform          vfs
builtins          inisetup          port_diag         webrepl
collections       io                random            webrepl_setup
cryptolib         json              re                websocket
deflate           lwip              requests/__init__
Plus any modules on the filesystem
'''
import socket
import network
import uasyncio as asyncio
import machine

html = """<!DOCTYPE html>
   <html>
       <head> <title>Micropython Web Server</title> </head>
       <body> <h1>Hello, World!</h1> </body>
   </html>"""
   
# 设置Socket并监听
def create_server():
    print('create socket')
    # 获取本地IP地址和端口号
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

    # 创建socket对象
    s = socket.socket()

    # 绑定地址和端口
    s.bind(addr)
    
    return s

pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)]
# 处理HTTP请求
def listen_connect(s, addr):
    print('listening on', addr)

    # 开始监听连接
    s.listen(5)

    while True:
        cl, addr = s.accept()
        print('client connected from', addr)
        cl_file = cl.makefile('rwb', 0)
        while True:
            line = cl_file.readline()
            if not line or line == b'\r\n':
                break
        rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
        response = html % '\n'.join(rows)
        cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        cl.send(response)
        cl.close()

    
    
    
    